package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * OrderTask
 *
 * @author liliudong
 * @version 1.0
 * @description 订单任务
 * @date 2023/8/7 9:30
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 每一分钟检查一次超时订单，并将其取消
     * 1.
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void orderTimeOut() {
        log.info("-----------超时订单定时任务：开始-----------");
        // // 1. 查：查询超时的订单列表 --> status = 1 时间超过15分钟
        // LocalDateTime now = LocalDateTime.now();
        // LocalDateTime plusMinutes = now.plusMinutes(-15);
        // List<Orders> ordersList = ordersMapper.selectListByStatusBeforeOrderTime(1, plusMinutes);
        // // 2. 改：修改超时订单状态 --> 6
        // ordersList.forEach(orders -> orders.setStatus(Orders.CANCELLED));
        // ordersMapper.updateBatch(ordersList);

        // 思考？直接把数据库里面状态为1的且时间<xx的状态更新为6
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime plusMinutes = now.plusMinutes(-15);
        Integer count = ordersMapper.updateStatusByStatusBeforeOrderTime(Orders.CANCELLED, Orders.PENDING_PAYMENT, plusMinutes);
        log.info("-----------超时订单定时任务：结束:{}-----------", count);
    }


    /**
     * 订单自动完成：每天晚上凌晨1点钟，自动将派送完成 4 的单子进行 完成 5
     * 对于非实时任务而言：推荐夜里执行
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void orderComplete() {
        log.info("------------订单自动完成:开始------------");
        Integer count = ordersMapper.updateStatusByStatus(Orders.COMPLETED, Orders.DELIVERY_IN_PROGRESS);
        log.info("------------订单自动完成:结束:{}------------", count);
    }
}
